<?php

namespace app\customer\logic;

use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use app\data\util\HttpUtil;
use think\facade\Db;
use util\Excel;
class OrderRefundLogic extends BasicLogic
{

    /**
     * @desc   获取发送消息配置列表接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function refundList($params=[]){
        $limit         = getIsset($params,'limit',10);
        $refund_status = $params['refund_status']??'';
        $shop_id       = $params['shop_id']??'';
        $operate_id    = $params['operater_id']??'';
        $order_id      = $params['order_id']??'';
        $order_number  = $params['order_number']??'';
        $is_part       = $params['is_part']??'';
        $SpecificReasons       = $params['SpecificReasons']??'';
        $create_time   = getIsset($params,'create_time');
        $where         = [];

        if(!empty($SpecificReasons)){
            $where[] = ['SpecificReasons','=',$SpecificReasons];
        }
        $where[] = ['shop_name','<>',""];
        if($refund_status!==''){
            $where[] = ['refund_status','=',$refund_status];
        }

        if($is_part!==''){
        $where[] = ['is_part','=',$is_part];
        }

        if($shop_id){
            $where[] = ['shop_id','=',$shop_id];
        }

        if($order_id){
            $order_ids_raw = trim($params['order_id']);
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');
            if (!empty($order_ids_filtered)) {
                $where[] = ['order_id', 'in', $order_ids_filtered];
            }
        }

        if($order_number){
            $order_numbers_raw = trim($params['order_number']);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            if (!empty($order_numbers_filtered)) {
                $where[] = ['order_number', 'in', $order_numbers_filtered];
            }
        }


        if($operate_id){
            $where[] = ['operate_id','=',$operate_id];
        }

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        $field = '*';
        $list   = Db::name('customer_refunds')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->group('order_id')
            ->paginate($limit);
        $lists = $list->items()?:[];

        $refundreason = Db::name('order_refundreason')->field('id,title')->select()->toarray();
        $refundreason = array_column($refundreason,'title','id');
        
        foreach ($lists as &$v) {
            $v['ReasonForRefund'] = $refundreason[$v['ReasonForRefund']] ?? '';
            switch ($v['refund_status']) {
                case '0':
                    $v['refund_status_msg'] = '待退款';
                    break;
                case '1':
                    $v['refund_status_msg'] = '退款中';
                    break;
                case '2':
                    $v['refund_status_msg'] = '退款成功';
                    break;
                case '3':
                    $v['refund_status_msg'] = '退款失败';
                    break;
                case '4':
                    $v['refund_status_msg'] = '已处理';
                    break;
                default:
                    $v['refund_status_msg'] = '未知';
            }
        }

        $data = [
            'list'   => $lists,
            'total'  => $list->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }

    /**
     * @desc   获取发送消息导出接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function exportrefundList($params=[]){
        $refund_status = $params['refund_status']??'';
        $shop_id       = $params['shop_id']??'';
        $operate_id    = $params['operater_id']??'';
        $order_id      = $params['order_id']??'';
        $order_number  = $params['order_number']??'';
        $is_part       = $params['is_part']??'';
        $SpecificReasons       = $params['SpecificReasons']??'';
        $create_time   = getIsset($params,'create_time');
        $where         = [];

        if(!empty($SpecificReasons)){
            $where[] = ['SpecificReasons','=',$SpecificReasons];
        }
        $where[] = ['shop_name','<>',""];
        if($refund_status!==''){
            $where[] = ['refund_status','=',$refund_status];
        }

        if($is_part!==''){
        $where[] = ['is_part','=',$is_part];
        }

        if($shop_id){
            $where[] = ['shop_id','=',$shop_id];
        }

        if($order_id){
            $order_ids_raw = trim($params['order_id']);
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');
            if (!empty($order_ids_filtered)) {
                $where[] = ['order_id', 'in', $order_ids_filtered];
            }
        }

        if($order_number){
            $order_numbers_raw = trim($params['order_number']);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            if (!empty($order_numbers_filtered)) {
                $where[] = ['order_number', 'in', $order_numbers_filtered];
            }
        }

        if($operate_id){
            $where[] = ['operate_id','=',$operate_id];
        }

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        $field = '*';
        $list   = Db::name('customer_refunds')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->group('order_id')
            ->select()->toarray();
        $refundreason = Db::name('order_refundreason')->field('id,title')->select()->toarray();
        $refundreason = array_column($refundreason,'title','id');
        
        foreach ($list as &$v) {
            $v['ReasonForRefund'] = $refundreason[$v['ReasonForRefund']] ?? '';
            switch ($v['refund_status']) {
                case '0':
                    $v['refund_status_msg'] = '待退款';
                    break;
                case '1':
                    $v['refund_status_msg'] = '退款中';
                    break;
                case '2':
                    $v['refund_status_msg'] = '退款成功';
                    break;
                case '3':
                    $v['refund_status_msg'] = '退款失败';
                    break;
                case '4':
                    $v['refund_status_msg'] = '已处理';
                    break;
                default:
                    $v['refund_status_msg'] = '未知';
            }
        }

        $header   = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单编号', 'order_number'];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['支付渠道', 'payment_gateway_names'];
        $header[] = ['退款金额', 'refund_payment'];
        $header[] = ['币种', 'currency'];
        $header[] = ['支付金额', 'payment'];
        $header[] = ['退款比例', 'refund_rate'];
        $header[] = ['发货状态', 'fulfillment_status'];
        $header[] = ['会话数量', 'conversations'];
        $header[] = ['操作人', 'operater'];
        $header[] = ['创建时间', 'create_time'];
        $header[] = ['支付时间', 'createtime'];
        $header[] = ['退款原因', 'ReasonForRefund'];
        $header[] = ['补充描述', 'Supplementary'];
        $header[] = ['退款意向', 'SpecificReasons'];
        $header[] = ['退款结果', 'refund_status_msg'];
        $header[] = ['SKU', 'skus'];
        $fileName = "order_refund_list".'_'.time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取发送消息导出接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function refundListLog($params=[]){
        $limit     = getIsset($params,'limit',10);
        $order_id  = $params['order_id']??'';
        $where         = [];
        $where[]       = ['order_id','=',$order_id];
        $field = '*';
        $res   = Db::name('customer_refunds_log')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $operater_ids    = array_column($list,'operate_id');
        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');
        //批量获取店铺名称;
        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');
        foreach($list as $k=>$v){
            $admin_users_info       = $admin_users_map[$v['operate_id']]??'';
            $list[$k]['operater']   = $admin_users_info['username']??'';
            $shopNames                = $shop_names_map[$v['shop_id']]??[];
            $shop_name                = $shopNames['name']??'';
            $list[$k]['shop_name']    = $shop_name;
            if($v['msg'] && $v['msg']!='创建中') {
                $list[$k]['msg'] = json_decode($v['msg'], true);
            }
            if($v['refund_id']){
                $list[$k]['msg'] = '退款成功';
            }
            $list[$k]['shop_name']    = $shop_name;
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);





    }


    /**
     * @desc   编辑接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function edit($params=[]){
        $id             = $params['id']??'';
        $refund_payment = $params['refund_payment']??0;
        Db::name('customer_refunds')->where(['id'=>$id])->update(
            [
            'refund_payment'     =>$refund_payment,
            'update_time'        =>date("Y-m-d H:i:s", time()),
         ]
        );
        return  $this->jsonMessage(200,true,'获取成功',null);

    }

    /**
     * @desc   获取批次列表接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function getBatchList($params=[]){
        $limit         = getIsset($params,'limit',10);
        $where          = [];
        $field = '*';
        $res   = Db::name('customer_refunds_batch')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取批次详情列表接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function getBatchDetailList($params=[]){
        $limit         = getIsset($params,'limit',10);
        $batch_id      = getIsset($params,'batch_id');
        $where         = [];
        $where[]       = ['batch_id','=',$batch_id];
        $field = '*';
        $res   = Db::name('customer_refunds_log')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $operater_ids    = array_column($list,'operate_id');
        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');
        //批量获取店铺名称;
        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');
        foreach($list as $k=>$v){
            $admin_users_info       = $admin_users_map[$v['operate_id']]??'';
            $list[$k]['operater']   = $admin_users_info['username']??'';
            $shopNames                = $shop_names_map[$v['shop_id']]??[];
            $shop_name                = $shopNames['name']??'';
            $list[$k]['shop_name']    = $shop_name;
            if($v['msg'] && !in_array($v['msg'],['创建中','该订单已退过款','退款成功','退款失败'])) {
                $list[$k]['msg'] = json_decode($v['msg'], true);
            }
            if($v['refund_id']){
                $list[$k]['msg'] = '退款成功';
            }
            $list[$k]['shop_name']    = $shop_name;
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取批次详情导出接口
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function exportBatchDetailList($params=[]){
        $batch_id      = getIsset($params,'batch_id');
        $where         = [];
        $where[]       = ['batch_id','=',$batch_id];
        $field = '*';
        $list   = Db::name('customer_refunds_log')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->select()
            ->toArray();
        $operater_ids    = array_column($list,'operate_id');
        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');
        //批量获取店铺名称;
        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');
        $refund_status  = [
            '0'=>'待退款',
            '1'=>'退款中',
            '2'=>'退款成功',
            '3'=>'退款失败',
            '4'=>'已处理',
        ];
        foreach($list as $k=>$v){
            $admin_users_info       = $admin_users_map[$v['operate_id']]??'';
            $list[$k]['operater']   = $admin_users_info['username']??'';
            $shopNames                = $shop_names_map[$v['shop_id']]??[];
            $shop_name                = $shopNames['name']??'';
            $list[$k]['shop_name']    = $shop_name;
            if($v['refund_id']){
                $list[$k]['msg'] = '退款成功';
            }
            $list[$k]['shop_name'] = $shop_name;
            $list[$k]['status']    = $refund_status[$v['status']]??'';
        }

        $header   = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单ID', 'order_id'];
        $header[] = ['订单编号', 'order_number'];
        $header[] = ['状态', 'status'];
        $header[] = ['退款金额', 'refund_payment'];
        $header[] = ['币种', 'currency'];
        $header[] = ['退款结果', 'msg'];
        $header[] = ['操作人', 'operater'];
        $header[] = ['创建时间', 'create_time'];
        $fileName = "order_refund_detail".'_'.time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }







    /**
     * @desc   导入数据处理
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function importInfo($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_ORDER_PAGE,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }


    /**
     * @desc   批量创建退款订单
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function batchRefund($params=[])
    {
        $ids     = $params['ids'];
        $adminId = $params['adminId'];
        htmlLog(['params' => $params], OPERATE_LOG . date('Ym') . '/batchRefund/' . date('Ymd') . '.txt');
        $url               =Config('Logisticskey.999_url').'/api/check/batch_refund_create';
        $info              = [
            'ids'       =>$ids,
            'adminId'   =>$adminId,
        ];
        $res               = HttpUtil::postDataCurl($url, $info);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }



    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2024-03-21
     */
    public function import_order_refund($params=[]){
        $key = 'import_order_refund:'.time();
        $redis_lock = new RedissLock();
        $lock = $redis_lock::lock($key, $redis_lock::UNBLOCK, 300);
        $order_number    =   getIsset($params,'order_number');
        $shop_name       =   getIsset($params,'shop_name');
        $refund_payment  =   getIsset($params,'refund_payment');
        $refund_payment  =   trim($refund_payment);
        //获取店铺ID和订单ID;
        $shop_name       =   trim($shop_name);
        $shop_infos      =   Config('Logisticskey.platform_shop');
        $shop_id         =   $shop_infos[$shop_name]??'';
        if(!$shop_id){
            $shop_id = Db::name('shops')->where(['name'=>$shop_name])->value('id');
        }
        if(!$shop_id){
            htmlLog(['params' => $shop_name], OPERATE_LOG . date('Ym') . '/import_order_shop_name/' . date('Ymd') . '.txt');
            return  ['msg'=>'暂无数据'];
        }
        $order_info      =    Db::name('order')->field('id,order_id')->where(['shop_id'=>$shop_id,'order_number'=>$order_number])->find();
        $order_id        =    $order_info['order_id']??'';
        if(!$order_id)  return  ['msg'=>'订单数据不匹配'];
        //查看当前$order_id是否退过款;
        $refund_id       = Db::name('order_transactions')
            ->where(['order_id'=>$order_id,'kind'=>'refund'])
            ->value('transactions_id');
        if(!$refund_id){
            $refund_id    = Db::name('customer_refunds')
                ->where(['order_id'=>$order_id])
                ->value('refund_id');
        }

        $refund_status   =    0;
        if($refund_id){
            $refund_status  = 4;
        }

        $payment_info  = Db::name('order_transactions')
            ->field('id,amount,currency')
            ->where(['order_id'=>$order_id])
            ->order('id desc')
            ->find();

        if(!$payment_info){
            return  ['msg'=>'暂无支付数据'];
        }

        $is_part = 0;

        //获取当前订单的total_price
        $total_price = Db::name('order')->where(['order_id'=>$order_id])->value('total_price');

        $amount = $payment_info['amount']??'';

        if($total_price && $amount){
              if($total_price - $amount>10){
                  $amount = $total_price;
              }
        }

        if($refund_payment< $amount){
            $is_part =1;
        }


        //数据入库逻辑
        $info = [
            'order_id'           =>$order_id,
            'order_number'       =>$order_number,
            'shop_id'            =>$shop_id,
            'refund_payment'     =>$refund_payment,
            'payment'            =>$amount,
            'currency'           =>$payment_info['currency'],
            'is_part'            =>$is_part,
            'refund_status'      =>$refund_status,
            'update_time'        =>date("Y-m-d H:i:s", time()),
            'create_time'        =>date("Y-m-d H:i:s", time()),
        ];
        //update 2024-08-27
        $res = Db::name('customer_refunds')->insertGetId($info);
        $lock->unlock();
        $info['status'] = $res == 1 ? 1:2;
        return  $info;
    }


    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){
        return [
            'shop_name'         => empty($row['A'])? '': trim($row['A']),
            'order_number'      => empty($row['B'])? '': trim($row['B']),
            'refund_payment'    => empty($row['C'])? '': trim($row['C']),
        ];
    }


    /**
     * @desc 退款处理消费方法
     * @author xx
     * @date 2024-03-21
     */
    public function order_refund_consumer($message){
            $shop_id          = $message['shop_id']??'';
            $order_id         = $message['order_id']??'';
            $currency         = $message['currency']??'';
            $amount           = $message['amount']??'';
            $operate_id       = $message['operate_id']??'';
            $id               = $message['id']??'';
            $batch_id         = $message['batch_id']??'';

            //查看当前$order_id是否退过款;
            $refund_id       = Db::name('order_transactions')
                               ->where(['order_id'=>$order_id,'kind'=>'refund'])
                               ->value('transactions_id');
            if(!$refund_id){
                $refund_id    = Db::name('customer_refunds_log')
                    ->where(['order_id'=>$order_id])
                    ->order('create_time asc')
                    ->value('refund_id');
            }

            if($refund_id){
                Db::name('customer_refunds_log')->where(['batch_id'=>$batch_id,'order_id'=>$order_id])->update(
                    [
                        'status'       =>4,
                        'msg'          =>'该订单已退过款',
                        'operate_id'   =>$operate_id,
                    ]
                );


                Db::name('customer_refunds')->where(['id'=>$id])->update(
                    [
                        'refund_status'=>4,
                        'operate_id'   =>$operate_id,
                        'update_time'  =>date("Y-m-d H:i:s", time()),
                    ]
                );
                return   true;
            }
            $shop_info        = Db::name('shops')->field('id,myshopify_domain,app_key,app_secret')->where(['id'=>$shop_id])->find();
            // 构建请求URL
            $url              = $shop_info['myshopify_domain'] . Config('Logisticskey.shopify.create_fullment_id') . $order_id . "/refunds.json";
            // 构建请求数据
            $data = [
                'refund' => [
                    'currency' => $currency,
                    'notify' => true,
                    'note' => "",
                    'transactions' => [
                        [
                            'amount'  => $amount,
                            'gateway' => "cash",
                            'kind'    => "refund",
                        ],
                    ],
                    'shipping' => [
                        'full_refund' => true,
                    ],
                ],
            ];
            // 发送POST请求
            $return     = HttpUtil::PostUrl($url, $data, $shop_info);

            $returnData = json_decode($return, true);
            htmlLog(['respose'=>$returnData,'order_id'=>$order_id],OPERATE_LOG . date('Ym') . '/order_refund_consumer/' . date('Ymd') . '.txt');
            $refund_id  = $returnData['refund']['id']??'';
            $errors     = $returnData['errors']??'';

            if($refund_id){ //退款成功
                Db::name('customer_refunds')->where(['id'=>$id])->update(
                    [
                        'refund_status'=>2,
                        'refund_id'    =>$refund_id,
                        'operate_id'   =>$operate_id,
                        'update_time'  =>date("Y-m-d H:i:s", time()),
                    ]
                );

                Db::name('customer_refunds_log')->where(['batch_id'=>$batch_id,'order_id'=>$order_id])->update(
                    [
                        'status'       =>2,
                        'msg'          =>'退款成功',
                        'refund_id'    =>$refund_id,
                        'operate_id'   =>$operate_id,
                    ]
                );
            }else{
                Db::name('customer_refunds')->where(['id'=>$id])->update(
                    [
                        'refund_status'=>3,
                        'operate_id'   =>$operate_id,
                        'update_time'  =>date("Y-m-d H:i:s", time()),
                    ]
                );

                Db::name('customer_refunds_log')->where(['batch_id'=>$batch_id,'order_id'=>$order_id])->update(
                    [
                        'status'       =>3,
                        'operate_id'   =>$operate_id,
                        'msg'          =>$errors ? json_encode($errors):'退款失败',
                    ]
                );
            }
            return true;
    }

     /**
     * @desc   移除待退款
     * @author zhangheng
     * @date   2025-03-17
     */
    public function del($params=[]){
        $id = $params['id']??'';
        if(!$id) {
            return  $this->jsonMessage(201,false,'ID不能为空',null);
        }
        Db::name('customer_refunds')->where(['id'=>$id])->delete();
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

}